// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Class to process inputs and templates.
 */


goog.provide('ads_mult.Processor');


/**
 * Class to process inputs and templates.
 * @param {Array.<Object>} inputs An Array of objects.
 *     Input properties are dependent on column names in spreadsheet.
 * @param {Array.<Object>} templates An Array of objects.
 *     Template properties are also dependent on column names.
 * @constructor
 */
ads_mult.Processor = function(inputs, templates) {
  this.inputs = inputs;
  this.templates = templates;
};


/**
 * Replaces all occurences of !!field with value in str.
 * Examples:
 * "Flights from !!city_dep to !!city_arr", "city_dep", "Denver" ->
 *     "Flights from Denver to !!city_arr"
 * "Flights from Denver to !!city_arr", "city_arr", "Chicago" ->
 *     "Flights from Denver to Chicago"
 * @param {string} str String that we need to replace values in.
 * @param {string} field Name of variable that we are looking for.
 * @param {string} value Value to replace field with.
 * @return {string} String with fields filled in.
 * @private
 */
ads_mult.Processor.fillString_ = function(str, field, value) {
  var patt = new RegExp('!!' + field, 'g');
  return str.replace(patt, value);
};


/**
 * Method to replace all instances of !!fieldName in the templates
 * with proper value from inputs.
 * Runs each line of input through each template to generate output.
 * If there are n inputs and m templates, generates nm rows of output.
 * @return {Array.<Object.<string,string>>} Array of values, where each set
 *     of inputs replaces variables in the template.
 */
ads_mult.Processor.prototype.process = function() {
  var outputs = [];

  for (var i = 0, input; input = this.inputs[i]; i++) {
    for (var j = 0, template; template = this.templates[j]; j++) {
      var out = {};
      // now look at each column
      for (var col in template) {
        var text = template[col];
        for (var field in input) {
          text = ads_mult.Processor.fillString_(text, field, input[field]);
        }
        out[col] = text;
      }
      outputs.push(out);
    }
  }
  return outputs;
};
